package com.wtao.imagereader;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.media.Image;
import android.media.ImageReader;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Surface;
import android.view.TextureView;
import android.widget.Toast;

import com.wtao.imagereader.camera.CameraV2Proxy;
import com.wtao.imagereader.utils.AutoFitTextureView;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public class CameraProxyActivity extends BaseActivity {
    String TAG = "CameraProxyActivity";
    private AutoFitTextureView mTextureView;
    CameraV2Proxy cameraV2Proxy;
    private final int PERMISSION_REQUEST_CODE = 100;
    private String[] permissions = new String[]{Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO};
    private List<String> mPermissionList = new ArrayList<>();
    int cameraId = 2;
    int previewWidth = 1920;
    int previewHeight = 1080;
    private boolean hasAllPermission() {
        mPermissionList.clear();
        if (Build.VERSION.SDK_INT < 23) {
            return true;
        }
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        return mPermissionList.size() <= 0;

    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*try {//特意主线程耗时2s，看是否有黑色底部背景出现，驾驶了延时，没有黑边
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        setContentView(R.layout.activity_camera_proxy);
        mTextureView = findViewById(R.id.texture);
        cameraV2Proxy = new CameraV2Proxy(this,mTextureView);
        findViewById(R.id.btnClose).setOnClickListener(v->{
            finish();
        });

        if (getIntent() != null) {
            String cameraIdStr = getIntent().getStringExtra("dmsCameraID");
            if (TextUtils.isEmpty(cameraIdStr)) {
                cameraIdStr = "1";
            }
            Log.e(TAG, "getIntent() != null cameraIdStr="+cameraIdStr);
            cameraId = Integer.parseInt(cameraIdStr);
            previewWidth = getIntent().getIntExtra("width", 1920);
            previewHeight = getIntent().getIntExtra("height", 1080);
        } else {
            cameraId = 2;
            previewWidth = 1920;
            previewHeight = 1080;
        }

        mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {

            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
                Log.e(TAG, "onSurfaceTextureAvailable: " + width + "----" + height);
                cameraV2Proxy.setPreviewSize(previewWidth,previewHeight);
                cameraV2Proxy.setCameraId(cameraId+"");
                cameraV2Proxy.setPreview(new Surface(mTextureView.getSurfaceTexture()), new ImageReader.OnImageAvailableListener() {
                    @Override
                    public void onImageAvailable(ImageReader reader) {
                        //Log.e(TAG, "onImageAvailable----->");
                        final Image image = reader.acquireLatestImage();   // 获取最近一帧图像
                        if(image!=null){//Attempt to invoke virtual method 'void android.media.Image.close()' on a null object reference
                            image.close();//这里需要关闭，不然会卡死预览界面
                        }

                    }
                });

                cameraV2Proxy.openCamera( );
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {

            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
                return true;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
            }

        });

        if (!hasAllPermission()) {
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
        }else { //第一次赋值过权限后，第二次打开界面，回走前面的代码打开摄像头

        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = false;
        Log.e(TAG, "onRequestPermissionsResult permissions.length="+permissions.length+" grantResults.length="+grantResults.length +" requestCode="+requestCode);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true;
                }
            }
            if (hasPermissionDismiss) {
                Toast.makeText(this, "请授予必要权限", Toast.LENGTH_SHORT).show();
            } else {
                if(cameraV2Proxy!=null){
                    //这里保证第一次打开app时，cameraV2Proxy没有打开摄像头但是这里再一次需要打开
                    cameraV2Proxy.openCamera();
                }
            }
        }
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cameraV2Proxy.releaseCamera();
    }
}